#############################################
#This file creates Figures OC1 and OC2
#############################################

###Log
my_log <- file("figure_oc1oc2_log.txt")

sink(my_log, append=T, type="output")
sink(my_log, append=T, type="message")

cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file
             file.info(rstudioapi::getSourceEditorContext()$path)$size))

start_time <- Sys.time()
start_time

############################
#Packages
############################
library(rio)
library(scales)
library(psych)
library(tidyverse)
library(broom)
library(ggstance)
library(socviz)
library(car)
library(magrittr)
library(multcomp)
library(margins)

################
#Experiment 1
################

####Load the data
exp1 <- import("./Data/exp1_cleaned.csv")

####Clean the data as needed
#DV
exp1$support01 <- scales::rescale(exp1$support)

#ID Strength
exp1$idstr <- scales::rescale(exp1$pid_idstr)
#Treatment Condition
exp1 <- exp1 %>%
  mutate(treat = case_when(
    condition == "No Party Cue" ~ 1, 
    condition == "Party Cue" ~ 2, 
    condition == "Neg Process" ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

#Experiment
exp1$experiment <- "Experiment 1"
exp1$pol_exp <- "Air Traffic"
exp1$treat_policy <- NA

################
#Experiment 2
################

####Load the data
exp2 <- import("./Data/exp2_cleaned.csv")
####Clean the data as needed
#DV
exp2$support01 <- scales::rescale(exp2$policy_support)

#Identity Strength
exp2$idstr <- scales::rescale(exp2$pid_idstr)

exp2 <- exp2 %>%
  mutate(treat = case_when(
    treat_info == 1 ~ 1, 
    treat_info == 2 ~ 2, 
    treat_info == 4 ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

exp2$treat_policy <- factor(exp2$treat_policy, 
                            levels=c(0,1),
                            labels=c("Conservative Change", "Liberal Change"))


#Experiment
exp2$experiment <- "Experiment 2"
exp2$pol_exp <- NA
exp2$pol_exp[exp2$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp2$pol_exp[exp2$treat_policy=="Liberal Change" ] <- "Tax:Liberal"

################
#Experiment 3
################

####Load the data
exp3 <- import("./Data/exp3_cleaned.csv")

####Clean the data as needed
#restrict to partisans
exp3 <- exp3 %>%
  filter(pid_3 == "Democrat" | pid_3 == "Republican")

#DV
exp3$support01 <- scales::rescale(exp3$tax_support)

#Identity Strength
exp3$idstr <- scales::rescale(exp3$pid_idstr)

#Treatment Condition(s)
exp3$treat <- factor(exp3$treat_3, 
                     levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                     labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))

exp3$treat_policy <- factor(exp3$change, 
                            levels=c("Conservative Change", "Liberal Change"))

#Experiment
exp3$experiment <- "Experiment 3"
exp3$pol_exp <- NA
exp3$pol_exp[exp3$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp3$pol_exp[exp3$treat_policy=="Liberal Change"] <- "Tax:Liberal"

################
#Pooled
################
exp1a <- exp1 %>%
  filter(pid_3 !=3, condition !="Pos Process") %>%
  dplyr::select(support01, idstr, treat, experiment, pol_exp, treat_policy) 
exp2a <- exp2 %>%
  filter(pid_3 !=3, treat_info !=3) %>%
  dplyr::select(support01, idstr, treat, experiment, pol_exp, treat_policy) 
exp3a <- exp3 %>%
  dplyr::select(support01, idstr, treat, experiment, pol_exp, treat_policy) 

pooled <- rbind(exp1a, exp2a, exp3a)

pooled <- pooled %>%
  mutate(experiment = factor(experiment,
                             levels=c("Experiment 1", "Experiment 2", "Experiment 3")))


pooled <- pooled %>%
  mutate(polissue = case_when(
    experiment == "Experiment 1" ~ 1, 
    experiment == "Experiment 2" & pol_exp == "Tax:Conservative" ~ 2,  
    experiment == "Experiment 2" & pol_exp == "Tax:Liberal" ~ 3, 
    experiment == "Experiment 3" & pol_exp == "Tax:Conservative" ~ 4, 
    experiment == "Experiment 3" & pol_exp == "Tax:Liberal" ~ 5), 
    polissue = factor(polissue, 
                      levels=c(1,2,3,4,5), 
                      labels=c("Experiment 1", "Exp 2: Conservative Change", 
                               "Exp 2: Liberal Change", "Exp 3: Conservative Change", 
                               "Exp 3: Liberal Change")))


export(pooled, "./Online Appendix C/pid_idstr_data.dta")


################
#Models & Margins
################
##Margins function
margid <- function(x) {
  summary(margins(x, 
                  at=list(idstr=c(0,0.25,0.5,0.75,1)), 
                  variables="treat"))
}

library(prediction)
predid <- function(x) {
  summary(prediction(x, 
                     at=list(treat = c("No Party Cue", "Party Cue", "Cue w/Insinuation"), 
                             idstr = c(0,0.25,0.5,0.75,1))))
}



##Models and margincalls
#Pooled
p1 <- lm(support01 ~ treat*idstr + polissue,  data=pooled)
p1_margs <- margid(p1) %>%
  mutate(model=  "Pooled")
p1_preds <- predid(p1) %>%
  mutate(model = "Pooled")

#Exp1 
p2 <- lm(support01 ~ treat*idstr, data = pooled, subset=(experiment == "Experiment 1"))
p2_margs <- margid(p2) %>%
  mutate(model = "Experiment 1")
p2_preds <- predid(p2) %>%
  mutate(model = "Experiment 1")

#Exp 2
p3 <- lm(support01 ~ treat*idstr + treat_policy, data = pooled, subset=(experiment == "Experiment 2"))
p3_margs <- margid(p3) %>%
  mutate(model = "Experiment 2")
p3_preds <- predid(p3) %>%
  mutate(model = "Experiment 2")

#Exp 3
p4 <- lm(support01 ~ treat*idstr + treat_policy, data = pooled, subset=(experiment == "Experiment 3"))
p4_margs <- margid(p4) %>%
  mutate(model = "Experiment 3")
p4_preds <- predid(p4) %>%
  mutate(model = "Experiment 3")

##Bind
margs <- rbind(p1_margs, p2_margs, p3_margs, p4_margs)
preds <- rbind(p1_preds, p2_preds, p3_preds, p4_preds)

margs$factor <- prefix_strip(margs$factor, "treat")

###Marginal Effect Figure
margs %>%
  mutate(model = factor(model, 
                        levels=c("Pooled", "Experiment 1", 
                                 "Experiment 2", "Experiment 3")), 
         factor = factor(factor, 
                         levels=c("Party Cue", "Cue w/Insinuation"))) %>%
  ggplot(aes(x=idstr, y=AME)) + 
  geom_pointrange(aes(ymin=lower, ymax=upper, shape=factor, color=factor), position = position_dodge(width=0.05)) + 
  geom_line(aes(color = factor), position = position_dodge(width=0.05)) + 
  theme_bw(18) + 
  facet_wrap(~ model) + 
  labs(x = "Identity Strength", 
       color = "Treatment", 
       shape = "Treatment") + 
  geom_hline(yintercept=0, linetype=2) + 
  theme(legend.position = "bottom" ) + 
  scale_color_manual(values = c("black", "red"))

ggsave("./Online Appendix C/figure_oc1.png", height=7, width=14)


####Predictions
preds %>%
  rename(idstr = `at(idstr)`, 
         factor = `at(treat)`) %>%
  mutate(model = factor(model, 
                        levels=c("Pooled", "Experiment 1", 
                                 "Experiment 2", "Experiment 3")), 
         factor = factor(factor, 
                         levels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))) %>%
  ggplot(aes(x=idstr, y=Prediction)) + 
  geom_pointrange(aes(ymin=lower, ymax=upper, shape=factor, color=factor), position = position_dodge(width=0.05)) + 
  geom_line(aes(color = factor), position = position_dodge(width=0.05)) + 
  theme_bw() + 
  facet_wrap(~ model) + 
  labs(x = "Identity Strength", 
       color = "Treatment", 
       shape = "Treatment") + 
  theme(legend.position = "bottom" ) + 
  scale_color_manual(values = c("black", "red", "grey"))

ggsave("./Online Appendix C/figure_oc2.png", height=7, width=14)




end_time <- Sys.time()
end_time

closeAllConnections()
  
  